<template>
  <div>
    <el-button type="primary">添加角色</el-button>
    <el-card class="box-card">
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限列  默认24份设置占5份-->
              <el-col :span="5"
                ><el-tag closable @close="removeTagById(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop ', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限列  -->
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="removeTagById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 三级权限列 -->
                  <el-col :sapn="11">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeTagById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="medium"
              circle
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="medium"
              circle
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="medium"
              circle
              @click="setRightDialogShow(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="权限分配"
      :visible.sync="setDialogVisible"
      width="30%"
      @close="setDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allogRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      setDialogVisible: false,
      rightsList: [],
      treeProps: {
        children: "children",
        label: "authName",
      },
      defkeys: [],
      roleID: [],
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      // console.log(this.rolesList);
      if (res.meta.status !== 200) {
        this.$message.error("获取数据失败");
      }
      this.rolesList = res.data;
    },
    async removeTagById(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除改文件，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("取消了删除"); //return 的作用是阻止向前编译
      }
      // console.log("确认了删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId})`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除角色失败");
      }
      role.children = res.data;
    },
    async setRightDialogShow(role) {
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限数据失败");
      }
      this.rightsList = res.data;
      // console.log(this.rightsList);

      this.getLeafKey(role, this.defkeys); //默认选项
      //为下面allogRights做准备
      this.roleID = role.id;

      this.setDialogVisible = true;
    },
    //获取第三组节点的id 根据展开的去匹配勾选
    getLeafKey(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((items) => {
        this.getLeafKey(items, arr);
      });
    },

    //分配权限关闭之后
    setDialogClosed() {
      this.defkeys = [];
    },
    //勾选的权限放到后端
    async allogRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleID}/rights`,
        {
          rids: idStr,
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("权限提交失败");
      }
      this.getRolesList();
      this.$message.success("权限提交成功");
      this.setDialogVisible = false;
    },
  },
};
</script>
<style scoped>
.el-card {
  margin-top: 20px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>